// pages/afterSale/form.js
let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    res:1,
    order_id: '',
    item_id: '',
    item_sku_id: '',
    orderItem: {},
    voucherList: [],
    reason: '',
    applyNumber: 1,
    serviceIndex: 1,
    getRefundBarterCheckTimer: 0,
    expressList: [],
    expressNo: '',
    expressIndex: -1,
    isFirst: true,
    serviceList: [{
        id: 10,
        name: '要求退款退货'
      },
      {
        id: 20,
        name: '更换相同商品'
      }
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const _this = this;
    console.log(options)
    this.setData({
      order_id: options.order_id,
      item_id: options.item_id,
      item_sku_id: options.item_sku_id,
      id: options.id || ''
    })

    App._post_form('refund_barter_check/getOrderInfo', {
      ...options
    }, function(result) {
      _this.setData({
        applyNumber: result.data.total_num,
        payPrice: result.data.pay_price,
        orderItem: result.data
      })
      // _this.getOrderList(_this.data.dataType);
    });
    if (options.id > 0) {
      _this.getRefundBarterCheck();
      const getRefundBarterCheckTimer = setInterval(() => {
        _this.getRefundBarterCheck();
      }, 10000)
      _this.setData({
        getRefundBarterCheckTimer: getRefundBarterCheckTimer
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(this.data.getRefundBarterCheckTimer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  getRefundBarterCheck: function() {
    const _this = this;
    App._post_form('refund_barter_check/getTimeInfo', {
      id: _this.data.id,
      order_id: _this.data.order_id,
      item_id: _this.data.item_id,
      item_sku_id: _this.data.item_sku_id
    }, function(result) {
      _this.setData({
        applyInfo: result.data.info,
        expressList: result.data.express_list

      })
      wx.nextTick(() => {
        _this.setData({
          applyTimeList: _this.nextHandle(result.data.list),
        })
      })
      // _this.getOrderList(_this.data.dataType);
    });
  },
  upload: function() {
    let _this = this;
    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        App._upload(tempFilePaths[0], function(res) {
          const result = JSON.parse(res);
          console.log(result)
          // let photoFile = _this.data.photoFile;
          const voucherList = _this.data.voucherList;
          voucherList.push(result.data);
          // photoFile[key] = result.data.file_path;
          _this.setData({
            voucherList: voucherList
          })
          // console.log(JSON.parse(res))
        })
      }
    })
  },
  deleteVoucher: function(e) {
    const _this = this;
    const index = e.currentTarget.dataset.index;
    const voucherList = _this.data.voucherList;
    voucherList.splice(index, 1)
    _this.setData({
      voucherList: voucherList
    })

  },
  bindServiceType: function(e) {
    this.setData({
      serviceIndex: e.detail.value
    })
  },
  submitApply: function() {
    const _this = this;
    const imgIds = [];
    for (let i in _this.data.voucherList) {
      imgIds.push(_this.data.voucherList[i].id);
    }

    const param = {
      order_id: _this.data.order_id,
      type: _this.data.serviceList[_this.data.serviceIndex].id,
      reason: _this.data.reason,
      img: imgIds.join(','),
      item_sku_id: _this.data.item_sku_id,
      item_num: _this.data.applyNumber,
      refund_money: _this.data.payPrice
    }
    wx.showLoading({
      title: '正在提交申请！',
    })
    App._post_form('refund_barter_check/submitAudit', {
      ...param
    }, function(result) {
      _this.setData({
        res: JSON.stringify(result)
      })
      if (result.code === 200) {
        wx.redirectTo({
          url: '/pages/afterSale/form?order_id=' + _this.data.order_id + '&item_id=' + _this.data.item_id + '&item_sku_id=' + _this.data.item_sku_id + '&id=' + result.data.id,
        })
      } else {
        App.showError(result.msg, function() {

        });
      }
      wx.hideLoading();

      // _this.getOrderList(_this.data.dataType);
    });

  },
  inputReason: function(e) {
    const _this = this;
    _this.setData({
      reason: e.detail.value
    })
  },
  calcApplyPrice: function() {
    this.setData({
      payPrice: this.data.orderItem.total_price * this.data.applyNumber / this.data.orderItem.total_num
    })
  },
  /**
   * 增加商品数量
   */
  up: function() {
    const _this = this;
    if (_this.data.applyNumber < _this.data.orderItem.total_num) {
      _this.setData({
        applyNumber: ++_this.data.applyNumber
      })
      wx.nextTick(() => {
        _this.calcApplyPrice();
      })
    }

  },

  /**
   * 减少商品数量
   */
  down: function() {
    const _this = this;
    if (_this.data.applyNumber > 1) {
      _this.setData({
        applyNumber: --_this.data.applyNumber
      });
      wx.nextTick(() => {
        _this.calcApplyPrice();
      })
    }
  },
  /**
   * 处理退款下一步显示
   */

  nextHandle: function(list) {
    const _this = this;
    const lastItem = list[0];
    let nextItem = {};
    console.log(lastItem)
    switch (lastItem.type) {
      case 'refund_submit':
        nextItem = {
          contentType: 'normalText',
          title: '退款申请已经提交',
          desc: '我们将在1~3个工作日进行审核，请留意。'
        };
        break;
      case 'barter_submit':
        nextItem = {
          contentType: 'normalText',
          title: '换货申请已经提交',
          desc: '我们将在1~3个工作日进行审核，请留意。'
        };
        break;
      case 'refund_error':
        nextItem = {
          contentType: 'rejectApply',
          title: `驳回理由：${_this.data.applyInfo.reject_reason}`,
          desc: '您可以点击右下角重新申请。'
        };
        break;
      case 'barter_error':
        nextItem = {
          contentType: 'rejectApply',
          title: `驳回理由：${_this.data.applyInfo.reject_reason}`,
          desc: '您可以点击右下角重新申请。'
        };
        break;
      case 'refund_check_success':
        nextItem = {
          contentType: 'writeDelivery',
          note: '请填写运单号'
        }
        break;
      case 'barter_success':
        nextItem = {
          contentType: 'writeDelivery',
          note: '请填写运单号'
        }
        break;
      case 'user_delivery_success':
        nextItem = {
          contentType: 'normalText',
          title: '等待快递寄送，我们将在收到退换货后第一时间为您处理',
          desc: '寄送时间根据快递运营商实际时间为主'
        }
        break;
      case 'refund_success':
        nextItem = {
          contentType: 'normalText',
          title: `已为您办理退款，退款金额${_this.data.applyInfo.refund_money}元`,
          desc: '我们将在24小时内将退款金额返回微信账户。'
        }
        break;
      case 'platform_receipt_success':
        nextItem = {
          contentType: 'normalText',
          title: '正在核验申请换货的商品是否满足退换货要求。',
          desc: '请耐心等候，并保持联系方式畅通'
        }
        break;
      case 'platform_delivery_success':
        nextItem = {
          contentType: 'waitUserReceipt',
          title: `已经换货商品寄出。\n快递公司：${_this.data.applyInfo.platform_express_company}。\n快递号${_this.data.applyInfo.platform_express_no}。`,
          desc: '收到后请点击“确认收货”完成售后服务'
        }
        break;


    }
    if (JSON.stringify(nextItem) !== '{}') {
      list.unshift(nextItem)
    }
    return list;
    console.log(list)
  },
  toRenewAfterSale: function(e) {
    const dataset = e.currentTarget.dataset
    let linkParams = 'order_id=' + this.data.order_id + '&item_id=' + this.data.item_id + '&item_sku_id=' + this.data.item_sku_id;
    wx.redirectTo({
      url: '/pages/afterSale/form?' + linkParams,
    })
  },
  copyExpress: function() {
    const _this = this;
    wx.setClipboardData({
      data: _this.data.applyInfo.platform_express_no,
      success(res) {
        wx.showToast({
          icon: 'none',
          title: `快递号：${_this.data.applyInfo.platform_express_no}\n已复制到系统剪贴板!`,
        })
      }
    })
  },
  saveExpressLog: function() {
    const _this = this;

    if (_this.data.expressIndex >= 0 || _this.data.expressNo) {
      const param = {
        id: _this.data.id,
        user_express_id: _this.data.expressList[_this.data.expressIndex].express_id,
        user_express_company: _this.data.expressList[_this.data.expressIndex].express_name,
        user_express_no: _this.data.expressNo
      }

      App._post_form('refund_barter_check/submitExpress', param, function(result) {
        if (result.code === 200) {
          wx.showToast({
            title: '提交成功',
            success: () => {
              _this.getRefundBarterCheck();
            }
          })
        } else {
          App.showError(result.msg, function() {

          });
        }
        // _this.getOrderList(_this.data.dataType);
      })
    }
  },
  changeExpress(e) {

    this.setData({
      expressIndex: e.detail.value
    })

  },
  inputExpressNo: function(e) {
    this.setData({
      expressNo: e.detail.value
    })
  },
  receiptProduct: function(e) {
    const _this = this;
    App._post_form('refund_barter_check/confirmReceipte', {
      id: _this.data.id
    }, function(result) {
      if (result.code === 200) {
        wx.showToast({
          title: '已完成售后',
          success: () => {
            _this.getRefundBarterCheck();
          }
        })
      } else {
        App.showError(result.msg, function() {

        });
      }
    })
  }

})